package mspbots.next.ticket.core.grader.interceptor;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.next.ticket.core.grader.AbstractGradeRuleAdapter;
import mspbots.next.ticket.core.grader.GradeRuleInterceptorRegistration;
import mspbots.next.ticket.core.points.PointResult;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;


@Log4j2
@Service(value = "TICKET_OWNER_POINT_RULE")
@RequiredArgsConstructor
public class TicketOwnerRuleInterceptor extends AbstractGradeRuleAdapter {

    private static final String RULE_KEY = "ticketOwner";
    private List<TicketOwnerParam> params;
    private String identifier;

    @Override
    public Mono<GradeRuleInterceptorRegistration> prepare(GradeRuleInterceptorRegistration gradeRuleInterceptorRegistration) {
        return Flux.just()
                .doFinally(r -> {
                    this.params = super.objectMapper
                            .convertValue(gradeRuleInterceptorRegistration.getRule().getParams(), new TypeReference<>() {
                            });
                    this.identifier = gradeRuleInterceptorRegistration.getRule().getRequest().getIdentifier();
                })
                .then(Mono.just(gradeRuleInterceptorRegistration));
    }

    @Override
    public Mono<PointResult> scoring(JsonNode ticket) {
        String ownerIdentifier = super.getStringValueIdentifier(ticket.get("owner"));
        int order = 0;
        if (StringUtils.hasLength(ownerIdentifier) && StringUtils.hasLength(this.identifier)
                && ownerIdentifier.equals(this.identifier)) {
            order = params.parallelStream().filter(TicketOwnerParam::isSelected)
                    .mapToInt(TicketOwnerParam::getPoints).sum();
        }

        return Mono.just(PointResult.withDefault().point(order)
                .detail(PointResult.Detail.with(order, Map.of("ownerIdentifier", ownerIdentifier), RULE_KEY)));
    }

    @Data
    static class TicketOwnerParam {
        private Integer index;
        private Integer points;
        private String condition;
        private boolean selected;
    }

}
